/**
 * Created by HuyNguyen on 6/12/14.
 */
var Main = function (){
    var $avatarDialog = $(".avatar-dialog"),
        $confirmDialog = $(".confirm-dialog"),
        imageCrop,
        languages = {},
        util = new UTIL();
    var avatarUrl = 'user/avatar';

    function findCulture(culture) {
        if (culture) {
            if (typeof culture === STRING) {
                var cultures = avatar.cultures;
                return cultures[culture] || cultures[culture.split("-")[0]] || null;
            }

            return null;
        }

        return null;
    }

    function getCulture(culture) {
        if (culture) {
            culture = findCulture(culture);
        }
        return culture || avatar.cultures.current;
    }

    var handleSideBar = function(){
        $('.sidebar-left ul.sidebar-menu li a').click(function() {
            "use strict";
            $('.sidebar-left li').removeClass('active');
            $(this).closest('li').addClass('active');
            var checkElement = $(this).next();
            if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
                $(this).closest('li').removeClass('active');
                checkElement.slideUp('fast');
            }
            if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
                $('.sidebar-left ul.sidebar-menu ul:visible').slideUp('fast');
                checkElement.slideDown('fast');
            }
            if($(this).closest('li').find('ul').children().length == 0) {
                return true;
            } else {
                return false;
            }
        });

        if ($(window).width() < 1025) {
            $(".sidebar-left").removeClass("sidebar-nicescroller");
            $(".sidebar-right").removeClass("right-sidebar-nicescroller");
            $(".nav-dropdown-content").removeClass("scroll-nav-dropdown");
        }
    }

    var handleToogle = function(){
        $(".btn-collapse-sidebar-left").click(function(){
            "use strict";
            $(".top-navbar").toggleClass("toggle");
            $(".sidebar-left").toggleClass("toggle");
            $(".page-content").toggleClass("toggle");
            $(".icon-dinamic").toggleClass("rotate-180");

            if ($(window).width() > 991) {
                if($(".sidebar-right").hasClass("toggle-left") === true){
                    $(".sidebar-right").removeClass("toggle-left");
                    $(".top-navbar").removeClass("toggle-left");
                    $(".page-content").removeClass("toggle-left");
                    $(".sidebar-left").removeClass("toggle-left");
                    if($(".sidebar-left").hasClass("toggle") === true){
                        $(".sidebar-left").removeClass("toggle");
                    }
                    if($(".page-content").hasClass("toggle") === true){
                        $(".page-content").removeClass("toggle");
                    }
                }
            }
        });

        $(".btn-collapse-sidebar-right").click(function(){
            "use strict";
            $(".top-navbar").toggleClass("toggle-left");
            $(".sidebar-left").toggleClass("toggle-left");
            $(".sidebar-right").toggleClass("toggle-left");
            $(".page-content").toggleClass("toggle-left");
        });

        $(".btn-collapse-nav").click(function(){
            "use strict";
            $(".icon-plus").toggleClass("rotate-45");
        });
    }

    var handleNiceScroll = function(){

        $(".sidebar-nicescroller").niceScroll({
            cursorcolor: "#121212",
            cursorborder: "0px solid #fff",
            cursorborderradius: "0px",
            cursorwidth: "0px"
        });
        $(".sidebar-nicescroller-visible-scroller").niceScroll({
            cursorcolor: "#121212",
            cursorborder: "0px solid #fff",
            cursorborderradius: "0px",
            cursorwidth: "5px",
            cursoropacitymax: 0.2
        });

        $(".sidebar-nicescroller").getNiceScroll().resize();

        $(".right-sidebar-nicescroller").niceScroll({
            cursorcolor: "#111",
            cursorborder: "0px solid #fff",
            cursorborderradius: "0px",
            cursorwidth: "0px"
        });

        $(".right-sidebar-nicescroller").getNiceScroll().resize();

        $(function () {
            "use strict";
            $('.scroll-nav-dropdown').slimScroll({
                height: '350px',
                position: 'right',
                size: '4px',
                railOpacity: 0.3
            });
        });


    }

    var handleBackToTop =  function(){

        $("#back-top").hide();

        $(window).scroll(function () {
            if ($(this).scrollTop() > 100) {
                $('#back-top').fadeIn();
            } else {
                $('#back-top').fadeOut();
            }
        });

        $('#back-top a').click(function () {
            $('body,html').animate({
                scrollTop: 0
            }, 800);
            return false;
        });
    }

    var handleLogOut = function(){
        $confirmDialog.on('show.bs.modal', function (e) {
            var $that = $(this),
                $item = $(e.relatedTarget);

            if($item.data("do") !== 'logout') return false;
            else{
                $('.confirm-dialog .modal-footer #confirmBtn').unbind('click');

                var title = $.trim($item.data("title"));
                var message = $.trim($item.data("message"));
                var logoutUrl = $.trim($item.data('href'));

                $('.modal-body p ', $that).text(message);
                $('.modal-title', $that).text(title);

                $('.modal-footer #confirmBtn',$confirmDialog).bind('click', function(){
                    $.ajax({
                        url:logoutUrl,
                        success: function(e){
                            window.location.reload();
                        }
                    })
                });
            }
        });
    }

    var initAvatarUpload = function(close){
        if(close){
            $avatarDialog.modal("hide");
            return true;
        }

        var $uploadImage = $('<div class="image-upload-and-crop-container">' +
            '<div class="image-explorer-container">' +
            '<div class="image-explorer-image-view" data-upload-prompt="Drag and drop image here">' +
            '<img class="image-explorer-source" />' +
            '<div class="avatar-white-bg"></div>' +
            '<div class="image-explorer-mask circle-mask" style=""></div>' +
            '<div class="image-explorer-drag-delegate ui-draggable"></div>' +
            '</div>' +
            '<div class="image-explorer-scale-slider-wrapper">' +
            '<input class="image-explorer-scale-slider" type="range" min="0" max="100" step="1" value="0">' +
            '</div>' +
            '</div>' +
            '<div class="avatar-bottom">' +
            '<input type="file" id="image-upload-and-crop-upload-field" class="image-upload-field" accept="image/jpeg, image/gif, image/png" style="display: none;">' +
            '<label for="image-upload-and-crop-upload-field" class="btn btn-default" style="float: right;margin-top: 20px">Select an image</label>' +
            '<button id="crop-button" class="btn btn-info" style="display: none;margin-top: 20px;margin-left:5px;float: right;">Use Avatar</button>' +
            '<button id="cancel-button" class="btn btn-danger" style="display: none;margin-top: 20px;float: right;">Cancel</button>' +

            '</div>' +
            '</div>');

        $(".modal-body", $avatarDialog).empty();
        $(".modal-body", $avatarDialog).html($uploadImage);

        var $cropButton = $("#crop-button");
        var  $output = $("#output");
        imageCrop = new ImageUploadAndCrop($(".image-upload-and-crop-container",$avatarDialog),
            {
                cropButton : $cropButton,
                onImageUpload : function(){
                    $('.image-upload-and-crop-container label[for="image-upload-and-crop-upload-field"]').hide();
                    $('#crop-button').show();
                    $('#cancel-button').show();
                },
                onCrop: function(croppedDataURI){
                    var data = dataURLToAB(croppedDataURI);
                    //console.log(data);
                    var blob = new Blob([data], {
                        type: 'image/jpeg'
                    });
                    var fd = new FormData(document.forms[0]);
                    fd.append("avatar", blob);
                    var request = {url: avatarUrl, data : fd}

                    var xhr = HttpRequest.send(request);

                }
            }
        );



        $('#cancel-button', $avatarDialog).unbind('click');
        $('#cancel-button', $avatarDialog).bind('click', function(e){
            initAvatarUpload(1);
        });

    };

    var initAvatarDialog = function(){
        $avatarDialog.on('show.bs.modal', function (e) {
            initAvatarUpload(0);

        });


    };

    var initModalPopupDrag = function(){
        $(".modal-dialog").draggable({});
        $(".modal").on("hidden.bs.modal", function(e){
            //window.alert('hidden event fired!');
           $(".modal-dialog",this).removeAttr("style");
          // var bootstrapValidator = $(form).data('bootstrapValidator');
        });
        $(".modal").on("hide.bs.modal", function(e){
            $('form', this).each(function(){
                this.reset();
                var bootstrapValidator = $(this).data('bootstrapValidator');
                if(typeof bootstrapValidator !=='undefined') bootstrapValidator.resetForm();
            });
            // var bootstrapValidator = $(form).data('bootstrapValidator');
        });
        $('.modal').on('shown.bs.modal', function () {


            $('form:first input[autofocus]', this).focus();
        })
    };



    return {
        init: function(language){
            //init language
            avatar.culture(language);
            kendo.culture(language);
            languages = new Language(language);

            //side bar initialize
            handleSideBar();
            //toogle button  initialize
            handleToogle();
            //nice scroll initialize
            handleNiceScroll();
            //back to top initialize
            handleBackToTop();
            //back to top initialize
            initAvatarDialog();

            initModalPopupDrag();



        },

        initCommonFunction: function(){
            handleLogOut();
        }
    }

}()
